package dao

import (
	"blogger/global"
	"blogger/model"
	"github.com/spf13/viper"
)

// 通过页码获取首页文章列表
func GetArticleListByPageNumber(pageNumber int) (*[]model.ArticleInfo, error) {
	pageSize := viper.GetInt("page.pageSize")
	var articleInfos []model.ArticleInfo
	sqlStr := "SELECT id, title, about, create_time FROM article where status = 0 ORDER BY create_time DESC LIMIT ?, ?"
	rows, err := global.DB.Query(sqlStr, (pageNumber-1)*pageSize, pageSize)
	if err != nil {
		panic(err.Error())
	}
	defer rows.Close()

	for rows.Next() {
		info := model.ArticleInfo{}
		dest := []interface{}{
			&info.Id,
			&info.Title,
			&info.About,
			&info.CreateTime,
		}
		err := rows.Scan(dest...)
		if err != nil {
			panic(err.Error())
		}
		articleInfos = append(articleInfos, info)
	}
	return &articleInfos, nil
}

// 读取当前所有文章数
func GetArticleListCount(status int) int {
	var count int
	sqlStr := "SELECT COUNT(*) FROM article WHERE status = ?"
	err := global.DB.QueryRow(sqlStr, status).Scan(&count)
	if err != nil {
		panic(err.Error())
	}
	return count
}
